package controller

import (
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"github.com/gin-gonic/gin"
	"os"
	"path/filepath"
	"restful-go/config"
	"restful-go/internal/utils"
	"time"
)

type Attachment struct {
	ID       uint   `json:"id"`
	FileName string `json:"file_name"`
	FilePath string `json:"file_path"`
	FileSize int64  `json:"file_size"`
}

func Upload(c *gin.Context) {
	// 获取上传的文件
	file, err := c.FormFile("file")
	if err != nil {
		utils.ErrorJSON(c, 400, fmt.Sprintf("无法获取上传的文件: %s", err.Error()))
		return
	}

	// 获取当前日期
	currentDate := time.Now().Format("2006-01-02") // 格式化为 "年-月-日"

	// 确定保存文件的目录
	rootDir, err := os.Getwd()
	if err != nil {
		utils.ErrorJSON(c, 422, "无法获取项目根目录")
		return
	}
	uploadDir := filepath.Join(rootDir, "resources", "uploads", currentDate)
	err = os.MkdirAll(uploadDir, 0755)
	if err != nil {
		utils.ErrorJSON(c, 422, fmt.Sprintf("无法创建文件夹: %s", err.Error()))
		return
	}

	ext := filepath.Ext(file.Filename)
	randomFileName, err := generateRandomFileName()

	// 确定保存文件的路径和名称
	filePath := filepath.Join(uploadDir, randomFileName+ext)

	// 保存上传的文件
	err = c.SaveUploadedFile(file, filePath)
	if err != nil {
		utils.ErrorJSON(c, 422, fmt.Sprintf("无法保存上传的文件: %s", err.Error()))
		return
	}

	attachment := Attachment{FileName: file.Filename, FilePath: os.Getenv("APP_URL") + "/" + filepath.ToSlash(filepath.Join("resources", "uploads", currentDate, randomFileName+ext)), FileSize: file.Size}
	config.Mysql.Create(&attachment)
	utils.SuccessJSON(c, gin.H{"id": attachment.ID, "filePath": attachment.FilePath})
	return
}

func generateRandomFileName() (string, error) {
	// 生成随机字节数组
	randomBytes := make([]byte, 16)
	_, err := rand.Read(randomBytes)
	if err != nil {
		return "", err
	}

	// 将字节数组转换为十六进制字符串
	fileName := hex.EncodeToString(randomBytes)

	return fileName, nil
}
